<template>
    <div>

        <el-table :data="inventoriesList" style="width: 100%">
            <el-table-column prop="inventoryId" label="ID" width="80"></el-table-column>
            <el-table-column prop="warehouseName" label="仓库名称"></el-table-column>
            <el-table-column prop="inventoryTakerName" label="盘点人姓名"></el-table-column>
            <el-table-column prop="countResult" label="盘点结果" width="150">
                <template #default="{ row }">
                    <!-- 下拉框绑定到row.countResult -->

                    <el-select v-model="row.countResult" placeholder="请选择" @change="handleInventoryStatusChange(row)" v-if="row.approvalStatus === '待审核'">
                        <el-option label="待盘点" value="0"></el-option>
                        <el-option label="正常" value="1"></el-option>
                        <el-option label="异常" value="2"></el-option>
                    </el-select>
                    <span v-else>{{ getInventoryStatus(row.countResult) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="inventoryDate" label="盘点日期" width="180">
                <template #default="{ row }">
                    {{ formatInventoryDate(row.inventoryDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="inventoryNotes" label="备注" width="180">
                <template #default="{ row }">
                    <!-- 输入框绑定到row.inventoryNotes -->
                    <el-input v-model="row.inventoryNotes" @blur="updateInventoryNotes(row)"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="approvalStatus" label="审批状态"></el-table-column>
            <el-table-column prop="approverName" label="审批人姓名"></el-table-column>
            <el-table-column prop="approvalDate" label="审批日期" width="180">
                <template #default="{ row }">
                    {{ formatApprovalDate(row.approvalDate) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template v-slot="scope">
                    <el-button type="text" @click="showInventoryDetails(scope.row)">查看盘点明细</el-button>
                    <el-button v-if="scope.row.countResult == '0'" type="text" @click="submitInventoryDetails(scope.row)">提交盘点明细</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 盘点明细模态框 -->
        <el-dialog v-model="dialogVisible" title="查看盘点明细">
            <!-- 使用 el-table 展示盘点明细数据 -->
            <el-table :data="inventoryDetails">
                <!-- 库存明细ID -->
                <el-table-column prop="inventoryDetailId" label="明细ID" width="80"></el-table-column>
                <!-- 盘点ID -->
                <el-table-column prop="inventoryId" label="盘点ID" width="80"></el-table-column>
                <!-- 产品ID -->
                <el-table-column prop="productId" label="产品ID" width="80"></el-table-column>
                <!-- 产品名称 -->
                <el-table-column prop="productName" label="产品名称"></el-table-column>
                <!-- 账面数量 -->
                <el-table-column prop="bookQuantity" label="账面数量"></el-table-column>
                <!-- 实际数量 -->
                <el-table-column prop="actualQuantity" label="实际数量"></el-table-column>
                <!-- 数量差异 -->
                <el-table-column prop="quantityDifference" label="数量差异"></el-table-column>
                <!-- 差异原因 -->
                <el-table-column prop="differenceReason" label="差异原因"></el-table-column>
            </el-table>
                <el-button @click="dialogVisible = false">确定</el-button>
        </el-dialog>
        <el-dialog v-model="dialogVisible2" title="填写盘点明细">
            <!-- 使用 el-table 展示盘点明细数据 -->
            <el-table :data="inventoryDetails">
                <!-- 库存明细ID -->
                <el-table-column prop="inventoryDetailId" label="明细ID" width="80"></el-table-column>
                <!-- 盘点ID -->
                <el-table-column prop="inventoryId" label="盘点ID" width="80"></el-table-column>
                <!-- 产品ID -->
                <el-table-column prop="productId" label="产品ID" width="80"></el-table-column>
                <!-- 产品名称 -->
                <el-table-column prop="productName" label="产品名称"></el-table-column>
                <!-- 账面数量 -->
                <el-table-column prop="bookQuantity" label="账面数量"></el-table-column>
                <!-- 实际数量 -->
                <el-table-column prop="actualQuantity" label="实际数量" width="120">
                    <template #default="{ row }">
                        <el-input v-model.number="row.actualQuantity" type="number"></el-input>
                    </template>
                </el-table-column>
                <!-- 数量差异 -->
                <el-table-column prop="quantityDifference" label="数量差异" width="120">
                    <template #default="{ row }">
                        <span>{{ Math.abs(row.bookQuantity - row.actualQuantity) }}</span>
                    </template>
                </el-table-column>
                <!-- 差异原因 -->
                <el-table-column prop="differenceReason" label="差异原因" width="200">
                    <template #default="{ row }">
                        <el-input v-model="row.differenceReason" ></el-input>
                    </template>
                </el-table-column>
            </el-table>
                    <el-button @click="sendInventory">确定</el-button>
        </el-dialog>
        <!-- 分页控件 -->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.currentPage"
                :page-size="page.pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
        >
        </el-pagination>
    </div>
</template>

<script setup>
    import {ref, reactive, computed, onMounted} from 'vue';
    import {getAllInventory,fillInventoryDetail,updateStatus} from '@/api/warehouse/invInventory';
    import {selectProduct} from '@/api/warehouse/invInventory'

    // 定义数据
    const loading = ref(false);
    const hidden = ref(false);
    // 定义模态框的显示状态和明细数据
    const dialogVisible = ref(false);
    let dialogVisible2 = ref(false);
    const inventoryDetails = ref([]);
    const inventoriesList = reactive([]);
    const inventoryVo = ref({
        warehouseId: '',
        inventoryTaKerId: '',
        inventoryTime: '',
        products: [],
    });
    const page = ref({
        total: 22,
        currentPage: 1,
        pageSize: 10,
    })
    inventoryDetails.value.forEach(item => {
        item.quantityDifference = computed(() =>
            item.bookQuantity - item.actualQuantity
        );
    });
    // 关闭模态框时重置明细数据
    function closeDialog() {
        inventoryDetails.value = [];
    }

    // 定义分页控件的事件处理函数
    function handleSizeChange(newSize) {
        page.value.pageSize = newSize;
        fetchInventory();
    }

    function handleCurrentChange(newPage) {
        page.value.currentPage = newPage;
        fetchInventory();
    }

    function selectInventory() {
        page.value.currentPage = 1;
        fetchInventory();
    }

    function fetchInventory() {
        inventoriesList.length = 0;
        const params = {
            ...inventoryVo.value, // 展开 inventoryVo.value 对象的所有属性
            currentPage: page.value.currentPage, // 当前页码
            pageSize: page.value.pageSize // 每页条数
        };
        getAllInventory(params).then(response => {
            loading.value = true; // 开始加载数据
            console.log(response.rows);
            page.value.total = response.total;
            const mappedRows = response.rows.map(inventory => ({
                inventoryId: inventory.inventoryId,
                warehouseId: inventory.warehouseId,
                warehouseName: inventory.warehouseName,
                inventoryTakerId: inventory.inventoryTakerId,
                inventoryTakerName: inventory.inventoryTakerName,
                countResult: inventory.countResult+"",
                inventoryDate: new Date(inventory.inventoryDate),
                inventoryNotes: inventory.inventoryNotes,
                approvalStatus: inventory.approvalStatus,
                approverName: inventory.approverName,
                approvalDate: inventory.approvalDate ? new Date(inventory.approvalDate) : null,
                whDetailedList: inventory.whDetailedList,
            }));
            inventoriesList.push(...mappedRows);
            loading.value = false;
        }).catch(error => {

            console.error('获取库存盘点失败:', error);
            // 这里可以添加错误处理逻辑，例如提示用户
        });

    }
    function updateInventoryNotes(row) {
        // 这里添加更新备注的逻辑
        updateStatus(row)
            .then(response => {
                // 成功更新后的处理
                row.inventoryNotes = response.invInventory.inventoryNotes;
                console.log('审核状态更新成功');
            })
            .catch(error => {
                // 错误处理
                console.error('审核状态更新失败:', error);
            });
        console.log('更新备注:', row.inventoryNotes);
        // 调用API或方法更新数据
    }

    function handleInventoryStatusChange(row) {
        // 这里添加处理盘点结果更改的逻辑
        console.log('盘点结果更改为:', row.countResult);
        updateStatus(row)
            .then(response => {
                // 成功更新后的处理
                row.countResult = getInventoryStatus(response.invInventory.countResult);
                console.log('审核状态更新成功');
            })
            .catch(error => {
                // 错误处理
                console.error('审核状态更新失败:', error);
            });

    }

    const showInventoryDetails = (row) => {
        inventoryDetails.value = [];
        row.whDetailedList.forEach((item) => {
            inventoryDetails.value.push(item);
        })
        dialogVisible.value = true;
    }
    const submitInventoryDetails = (row) =>{
        inventoryDetails.value = [];
        row.whDetailedList.forEach((item) => {
            inventoryDetails.value.push(item);
        })
        dialogVisible2.value = true;
    }
    const sendInventory = () =>{

        console.log(inventoryDetails.value)
        fillInventoryDetail(inventoryDetails.value).then(() => {
            fetchInventory();
        }).catch(error => {
            console.error('提交明细失败:', error);
        })
        dialogVisible2.value = false;
    }

    // 定义日期格式化方法
    function formatInventoryDate(date) {
        return date.toLocaleString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit'});
    }

    function formatApprovalDate(date) {
        if (!date || isNaN(date)) {
            return '';
        }
        return date.toLocaleString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit'});
    }

    //新增计算属性或方法来转换countResult
    function getInventoryStatus(countResult) {
        switch (countResult) {
            case "0":
                return '待盘点';
            case "1":
                return '正常';
            case "2":
                return '异常';
            case 0:
                return '待盘点';
            case 1:
                return '正常';
            case 2:
                return '异常';
            default:
                return '未知状态';
        }
    }


    // 定义加载数据的方法
    function loadOptions() {
        fetchInventory();
    }

    onMounted(() => {
        // 初始化逻辑
        loadOptions();
        //fetchInventory();
    });
</script>

<style scoped>

</style>